package com.itheima.web.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Freeze;
import com.itheima.domain.db.UnFreeze;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.FreezeService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.CommentVo;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.*;

@Component
public class UserManager {

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private FreezeService freezeService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;




    //分页查询用户信息
    public ResponseEntity findUserinfoByPage(Integer pageNum, Integer pageSize) {


        PageBeanVo pageBeanVo = userInfoService.findByPage(pageNum, pageSize);

        List<UserInfo> userInfoList = (List<UserInfo>) pageBeanVo.getItems();

        if (CollectionUtil.isNotEmpty(userInfoList)) {
            for (UserInfo userInfo : userInfoList) {
                if (!stringRedisTemplate.hasKey(ConstantUtil.FREEZE_LOGIN + userInfo.getId()) &&
                        !stringRedisTemplate.hasKey(ConstantUtil.FREEZE_COMMENT + userInfo.getId()) &&
                        !stringRedisTemplate.hasKey(ConstantUtil.FREEZE_PUBLISH + userInfo.getId())) {
                    userInfo.setUserStatus("1");
                }
            }
        }
        pageBeanVo.setItems(userInfoList);

        return ResponseEntity.ok(pageBeanVo);

    }

    //用户详情
    public ResponseEntity findUserInfoById(Long userId) {
        UserInfo userinfo = userInfoService.findById(userId);
        return ResponseEntity.ok(userinfo);
    }


    @DubboReference
    private MovementService movementService;



    // 动态列表
    public ResponseEntity findMovementVoByPage(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        // 1.调用rpc查询
        PageBeanVo pageBeanVo = movementService.findMovementByPage(userId, state, pageNum, pageSize);
        // 2.封装vo
        // 2-1 声明voList
        List<MovementVo> voList = new ArrayList<>();
        // 2-2 获取movementList
        List<Movement> movementList = (List<Movement>) pageBeanVo.getItems();
        // 2-3 遍历movementList
        if (CollectionUtil.isNotEmpty(movementList)) {
            for (Movement movement : movementList) {
                // 查询userInfo
                UserInfo userInfo = userInfoService.findById(movement.getUserId());
                // 创建vo
                MovementVo vo = new MovementVo();
                vo.setUserInfo(userInfo);
                vo.setMovement(movement);
                // 自定义时间
                vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));
                // 添加到集合
                voList.add(vo);
            }
        }
        // 3.将voList设置到分页对象
        pageBeanVo.setItems(voList);
        // 4.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    //动态详情
    public ResponseEntity findMovementVoById(String publishId) {
        Movement movement = movementService.findById(new ObjectId(publishId));

        MovementVo vo = new MovementVo();

        UserInfo userinfo = userInfoService.findById(movement.getUserId());

        vo.setUserInfo(userinfo);
        vo.setMovement(movement);
        vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));

        return ResponseEntity.ok(vo);
    }

    @DubboReference
    private CommentService commentService;

    //评论列表
    public ResponseEntity findCommentVoByPage(Integer pageNum, Integer pageSize, String publishId) {
        PageBeanVo pageBeanVo = commentService.findCommentByPage(new ObjectId(publishId), 2, pageNum, pageSize);

        List<CommentVo> voList = new ArrayList<>();

        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();

        if (CollectionUtil.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {

                // 查询userInfo
                UserInfo userInfo = userInfoService.findById(comment.getUserId());
                // 创建vo
                CommentVo vo = new CommentVo();
                vo.setId(comment.getId().toHexString());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setContent(comment.getContent());
                vo.setCreateDate(DateUtil.formatDateTime(new Date(comment.getCreated())));
            }
        }

        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    @DubboReference
    private VideoService videoService;
    //后台视频分页
    public ResponseEntity findVideoByPage(Integer pageNum, Integer pageSize, String sortProp, String sortOrder, Long userId) {

        PageBeanVo pageBeanVo = videoService.findVideoByPage(pageNum, pageSize, sortProp, sortOrder, userId);

        List<VideoVo> voList = new ArrayList<>();

        List<Video> videos = (List<Video>) pageBeanVo.getItems();

        if (CollectionUtil.isNotEmpty(videos)) {
            for (Video video : videos) {
                UserInfo userInfo = userInfoService.findById(video.getUserId());
                VideoVo vo = new VideoVo();
                vo.setUserInfo(userInfo);
                vo.setVideo(video);
                voList.add(vo);
            }
        }
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }
    //冻结
    public ResponseEntity saveFreeze(Freeze freeze) {
        Long userId = freeze.getUserId();
        UserInfo userInfo = userInfoService.findById(userId);
        userInfo.setUserStatus("2");
        userInfoService.update(userInfo);

        Map<String, String> map = new HashMap<>();

            map.put("message", "操作成功");
            Integer freezingTime = freeze.getFreezingTime();
            Integer freezingRange = freeze.getFreezingRange();
            String json = JSON.toJSONString(freeze);
            if (freezingTime == 1) {//封禁三天
                if (freezingRange == 1) {
                    //封禁登录
                    stringRedisTemplate.opsForValue().set("freeze_login_"+String.valueOf(userId),json, Duration.ofDays(3));
                } else if (freezingRange == 2) {
                    //封禁评论
                    stringRedisTemplate.opsForValue().set("freeze_comment_" + String.valueOf(userId), json, Duration.ofDays(3));
                } else {
                    //封禁发布动态
                    stringRedisTemplate.opsForValue().set("freeze_publish_" + String.valueOf(userId), json, Duration.ofDays(3));
                }
            } else if (freezingTime == 2) {//封禁七天
                if (freezingRange==1) {
                    stringRedisTemplate.opsForValue().set("freeze_login_" + String.valueOf(userId), json, Duration.ofDays(7));
                } else if (freezingRange == 2) {
                    stringRedisTemplate.opsForValue().set("freeze_comment_" + String.valueOf(userId), json, Duration.ofDays(7));
                } else {
                    stringRedisTemplate.opsForValue().set("freeze_publish_" + String.valueOf(userId), json);
                }
            } else {//封禁永久
                if (freezingRange == 1) {
                    stringRedisTemplate.opsForValue().set("freeze_login_" + String.valueOf(userId), json);
                } else if (freezingRange == 2) {
                    stringRedisTemplate.opsForValue().set("freeze_comment_" + String.valueOf(userId), json);
                } else {
                    stringRedisTemplate.opsForValue().set("freeze_publish_" + String.valueOf(userId), json);
                }
            }

            return ResponseEntity.ok(map);

    }
    //解冻
    public ResponseEntity unFreeze(UnFreeze unFreeze) {
        Long userId = unFreeze.getUserId();
        stringRedisTemplate.delete(ConstantUtil.FREEZE_LOGIN + userId);
        stringRedisTemplate.delete(ConstantUtil.FREEZE_PUBLISH + userId);
        stringRedisTemplate.delete(ConstantUtil.FREEZE_COMMENT + userId);
        UserInfo userInfo = userInfoService.findById(userId);
        userInfo.setUserStatus("1");
        userInfoService.update(userInfo);
        Map<String, String> map = new HashMap<>();
        map.put("message", "操作成功");
        return ResponseEntity.ok(map);
    }


    //动态通过
    public ResponseEntity passMovement(List<String> ids) {
        Map<String, String> map = new HashMap<>();
        if (CollectionUtil.isNotEmpty(ids)) {
            for (String id : ids) {
                Movement movement = movementService.findById(new ObjectId(id));
                movement.setState(1);
                movementService.updateMovement(movement);
            }
        }
        map.put("message","操作成功");
        return ResponseEntity.ok(map);
    }
    //动态拒绝
    public ResponseEntity unPassMovement(List<String> ids) {
        Map<String, String> map = new HashMap<>();
        if (CollectionUtil.isNotEmpty(ids)) {
            for (String id : ids) {
                Movement movement = movementService.findById(new ObjectId(id));
                movement.setState(2);
                movementService.updateMovement(movement);
            }
        }
        map.put("message","操作成功");
        return ResponseEntity.ok(map);

    }
}
